<?php
/**
 * Created by LíJimpéy(：
 * User: jimpey88
 * Date: 2024/3/28
 * Email: < jimpey@qq.com >
 * Project: company-admin-tp6
 */
declare (strict_types = 1);

namespace app\backend_api\middleware;

use app\backend_api\services\JwtTokenService;
use app\common\Services\JsonService;
use Psr\SimpleCache\InvalidArgumentException;
use think\facade\Cache;

class AuthCheck
{
    use JsonService;

    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @return \think\response\Json
     * @throws InvalidArgumentException
     */
    public function handle($request, \Closure $next)
    {
        // 获取token
        $token = $request->header('Authorization', '');
//        dd($token);
        if (!$token) {
            return $this->error('请先登录！', 401, 401);
        }
        $token = trim(substr($token, 6)); // 去除 Bearer 字段


        $tokenInfo = JwtTokenService::checkToken($token);
        if ($tokenInfo['code'] != 1) {
            return $this->error($tokenInfo['msg'], 401, 401);
        }

        $adminId = $tokenInfo['data']->uid;
        // 因为jwt无状态，所以加上redis管理登录状态
//        $cacheToken = Cache::store('redis')->get('admin_id_'.$adminId);
//        if (!$cacheToken || $token != $cacheToken) {
//            return $this->error('token已失效，请重新登录！', 401, 401);
//        }

        $request->admin_id = $adminId;

        return $next($request);
    }
}
